package com.colorlight.cloud.complete.entity.event;

import com.colorlight.cloud.complete.api.CompleteEntityEvent;
import com.colorlight.cloud.complete.entity.enumerate.DownloadResult;
import com.colorlight.cloud.complete.entity.po.Download;
import com.colorlight.iot.proto.complete.entity.CompleteEntity;
import com.colorlight.iot.proto.complete.event.CompleteEvent;
import com.google.protobuf.ByteString;
import com.google.protobuf.InvalidProtocolBufferException;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;

/**
 * 下载结果上报
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Slf4j
public class DownloadReport implements CompleteEntityEvent {

    /**
     * 当前下载结果
     */
    private DownloadResult result;

    /**
     * 下载百分比，下载中<100,下载成功=100
     */
    private Integer percent;

    /**
     * 下载信息
     */
    private Download download;

    @Override
    public DownloadReport byteConvertObject(ByteString bytes) {
        CompleteEvent.DownloadReport downloadReport = null;
        try {
            downloadReport = CompleteEvent.DownloadReport.parseFrom(bytes);
        } catch (InvalidProtocolBufferException e) {
            log.error("", e);
        }
        Objects.requireNonNull(downloadReport);
        CompleteEntity.DownloadResult downloadResult = downloadReport.getResult();
        this.setResult(DownloadResult.getDownloadResultStruct(downloadResult));
        this.setPercent(downloadReport.getPercent());
        this.setDownload(new Download().formProto(downloadReport.getDownload()));
        return this;
    }
}

